package com.alibaba.shopping_order_customer_api.controller;

import com.alibaba.fastjson2.JSON;
import com.alibaba.shopping_common.pojo.Orders;
import com.alibaba.shopping_common.pojo.Payment;
import com.alibaba.shopping_common.result.BaseResult;
import com.alibaba.shopping_common.service.AlipayService;
import com.alibaba.shopping_common.service.OrderService;
import jakarta.servlet.http.HttpServletRequest;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.HashMap;

/**
 * @ClassName PaymentController
 * @Description TODO
 * @Author Leo
 * @Date 2024/12/19 14:35
 */
@RestController
@RequestMapping("/user/payment/")
public class PaymentController {

    @DubboReference
    private AlipayService alipayService;

    @DubboReference
    private OrderService orderService;

    /**
     * 获取支付的二维码
     * @param orderId
     * @return
     */
    @PostMapping("/pcPay")
    public BaseResult<String> pcPay(String orderId){
        Orders orders = orderService.findById(orderId);
        String codeUrl = alipayService.pcPay(orders);
        return BaseResult.OK(codeUrl);
    }


    // @GlobalTransactional // 对该方法开启分布式事务管理
    @PostMapping("/success/notify")
    public BaseResult successNotify(HttpServletRequest request){
        // 1. 验签
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("requestParamMap",request.getParameterMap());
        alipayService.checkSign(paramMap);

        String trade_status = request.getParameter("trade_status");
        String out_trade_no = request.getParameter("out_trade_no");
        if (trade_status.equals("TRADE_SUCCESS")){
            // 修正订单状态
            Orders orders = orderService.findById(out_trade_no);
            // 订单状态为已付款
            orders.setStatus(2);
            // 支付方式：支付宝
            orders.setPaymentType(2);
            // 支付时间
            orders.setPaymentTime(new Date());
            //
            orderService.updateOrder(orders);

            // 模拟出现异常
            int i = 1/0;

            // 添加交易记录
            Payment payment = new Payment();
            // 订单编号
            payment.setOrderId(out_trade_no);
            // 交易编号
            payment.setTransactionId(out_trade_no);
            payment.setTradeType("支付宝支付");
            payment.setTradeState(trade_status);
            // 交易总金额
            payment.setPayerTotal(orders.getPayment());
            payment.setContent(JSON.toJSONString(request.getParameterMap()));
            // 创建时间
            payment.setCreateTime(new Date());
            // 创建交易记录
            alipayService.addPayment(payment);
        }
        return BaseResult.OK();
    }

}




